import random
import datetime
from flask import Blueprint, request, jsonify

from models.miniprogram_model import Round

bp = Blueprint('mysqlchart', __name__, url_prefix='/mysqlchart')

@bp.route('/get_test_data', methods=['Post'])
def get_chart_data():
    # 模拟数据
    labels = [(datetime.datetime.now() - datetime.timedelta(days=i)).strftime('%m-%d')for i in range(7)][::-1]
    values = [random.randint(-1000, 1000) for _ in range(7)]
    # print(labels)
    # print(values)
    # ['07-11', '07-12', '07-13', '07-14', '07-15', '07-16', '07-17']
    # [845, 289, 560, 556, 239, 992, 809]
    return jsonify(
        {
        'labels': labels,
        'values': values
        }
    )

@bp.route('/get_test_data1', methods=['Post'])
def get_chart_data1():
    try:
        rounds = Round.query.filter_by(room_id="e5174c84-54fb-4f9a-a13a-0609da0a40ec").order_by(
            Round.round_number.asc()).all()
        # 构建对象数组格式
        source = []
        for r in rounds:
            source.append({
                'round_number': r.round_number,
                'user1_score': r.user1_score or 0,
                'user2_score': r.user2_score or 0,
                'user3_score': r.user3_score or 0,
                'user4_score': r.user4_score or 0
            })
        return jsonify({
            'success': True,
            'data': {
                'dataset': {
                    'source': source
                }
            }
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e),
            'data': None
        })

@bp.route('/get_dashboard_data')
def get_dashboard_data():
    return jsonify({
        'totalVisits': 12543,
        'newUsers': 864,
        'conversionRate': 3.2,
        'avgTime': '6:42',
        'visitsGrowth': 12.5,
        'usersGrowth': 8.2,
        'conversionChange': -2.1,
        'timeGrowth': 5.3
    })